<template>
  <div>
    <RelationSection title="关联映射">
      <div>
        <a-button @click="clear" type="link">清空映射</a-button>
        <MappingRules/>
      </div>

      <div style="padding-left: 20px" :key="manual.id" v-for="(manual, index) in innerManuals">
        <div class="manual-relation-mapping-button-wrapper">
          <a-button size="small" icon="plus" @click="() => addNew(index)"/>
          <a-button size="small" icon="minus" style="margin-left: 10px" @click="() => remove(manual)"/>
        </div>
        <FieldContrastConfig
          :source-form-definition="formDefinition" @leftChange="leftChange"
          :target-form-definition="relationTargetFormDefinition" @removed="resolveManualSelector"
          :include-target-forms="relation.relationTargetInnerFormId"
          v-model="manual.fieldBinds" :exclude-source-forms="getExcludeSourceForms(index)">
          <template slot="leftButton" slot-scope="{fieldContrast}">
            <a-icon type="exclamation" v-show="!hasConfigSelector(manual) && isSelectorField(fieldContrast, manual)"
                    style="color: red"/>
            <a-button
              :class="['manual-relation-mapping-icon',{'manual-relation-mapping-selected-field': isSelectorField(fieldContrast, manual)}]"
              @click="() => handleSelectorClick(isSelectorField(fieldContrast, manual), manual, fieldContrast)"
              icon="file-search" size="small" type="link"/>
          </template>
        </FieldContrastConfig>
        <div v-show="index < innerManuals.length - 1" class="manual-relation-mapping-divider"/>
      </div>
    </RelationSection>

    <RelationSelectorConfig
      :relation="relation"
      :source-form-definition="formDefinition"
      :target-form-definition="relationTargetFormDefinition"
      ref="RelationSelectorConfig"/>
  </div>
</template>
<script>
import RelationSection from '@comp/hhd/design/relation/RelationSection/RelationSection.vue';
import FieldContrastConfig from '@comp/hhd/design/relation/FieldContrastConfig/FieldContrastConfig.vue';
import {createProps} from '@/utils';
import {createManual, createRelation} from '@comp/hhd/design/relation/types';
import {createFormDefinition} from '@comp/hhd/design/FormDesigner/types';
import MappingRules from '@comp/hhd/design/relation/MappingRules/MappingRules.vue';
import RelationSelectorConfig from '@comp/hhd/design/relation/RelationSelectorConfig/RelationSelectorConfig.vue';

export default {
  name: 'ManualRelationMapping',
  components: {RelationSelectorConfig, MappingRules, FieldContrastConfig, RelationSection},
  props: {
    labelWidth: createProps(String),
    relation: createProps(Object, createRelation),
    formDefinition: createProps(Object, createFormDefinition),
    relationTargetFormDefinition: createProps(Object, createFormDefinition)
  },
  methods: {
    clear() {
      this.relation.manuals = [];
    },
    addNew(index) {
      this.relation.manuals.splice(index + 1, 0, createManual());
    },
    leftChange() {
      this.$nextTick(() => {
        this.relation.manuals.splice(0, 0);
        this.resolveManualSelector();
      });
    },
    resolveManualSelector() {
      this.relation.manuals.forEach(manual => {
        if (!manual.manualSelectorFieldId) return;
        let fieldBinds = manual.fieldBinds || [];
        let fieldBind = fieldBinds.find(f => f.sourceFieldId === manual.manualSelectorFieldId);

        if (!fieldBind) {
          manual.manualSelectorFieldId = undefined;
          manual.manualSelectorButtonName = undefined;
        }
      });
    },
    remove(item) {
      this.relation.manuals = this.relation.manuals.filter(m => m !== item);
    },
    hasConfigSelector(manual) {
      if (!manual.fieldColumns || !manual.fieldColumns.length) {
        return false;
      }
      return true;
    },
    isSelectorField(fieldContrast, manual) {
      return fieldContrast.sourceFieldId && (fieldContrast.sourceFieldId === manual.manualSelectorFieldId);
    },
    handleSelectorClick(isSelectorField, manual, fieldContrast) {
      if (!fieldContrast.sourceFieldId) return this.$message.warn('请先设置映射字段');
      if (!isSelectorField) {
        manual.manualSelectorFieldId = fieldContrast.sourceFieldId;
        return;
      }
      this.$refs.RelationSelectorConfig.setData(manual);
    },
    getExcludeSourceForms(index) {
      if (!this.relation.manuals || !this.relation.manuals.length) return [];
      let res = new Set();
      for (let i = 0; i < this.relation.manuals.length; i++) {
        if (i === index) continue;
        let fieldBinds = this.relation.manuals[i].fieldBinds || [];
        fieldBinds.forEach(bind => {
          bind.sourceFormId && res.add(bind.sourceFormId);
        });
      }

      return [...res];
    },
  },
  computed: {
    innerManuals: {
      get() {
        if(this.relation.relationType !== 'manual') return []
        let res = this.relation.manuals;
        if (!res) res = this.relation.manuals = [createManual()];
        if (!res.length) {
          res.push(createManual());
        }
        return res;
      },
      set(v) {
        this.relation.manuals = v;
      },
    }
  }
};
</script>
<style>
.manual-relation-mapping-button-wrapper {
  text-align: right;
}

.manual-relation-mapping-divider {
  height: 1px;
  background: #d4d4d4;
  margin: 10px 0;
}

.manual-relation-mapping-icon .anticon {
  color: #cccccc;
}

.manual-relation-mapping-selected-field .anticon {
  color: #1f85ec
}
</style>